package com.taru.controller;

import com.taru.utils.JsonResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

@Controller
@ResponseBody
public class imageUpController {
    @RequestMapping("/user/upload")
    public Object upload(@RequestParam("file")MultipartFile file)
    {
        JsonResult jsonResult=null;
        try {
            if (!file.isEmpty()){
                String oldFileName=file.getOriginalFilename();
                String newFileName=String.valueOf(System.currentTimeMillis())+oldFileName.substring(oldFileName.lastIndexOf("."));
                InputStream is=file.getInputStream();
                BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\image"+ File.separator+newFileName));
                byte [] bs=new  byte[1024];
                int len;
                while ((len=is.read(bs))!=-1){
                    bos.write(bs,0,len);
                }
                bos.flush();
                bos.close();
                jsonResult=new JsonResult("200","成功",newFileName);
            }else
            {
                jsonResult=new JsonResult("404","失败");
            }
        }catch (Exception e){
            jsonResult=new JsonResult("500","错误");
        }

        return jsonResult;
    }


}
